package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {
    private Socket socket;
    private String method;
    private String uri;
    private String protocol;

    private String requestURI;
    private String queryString;

    private Map<String,String> parameters = new HashMap<>();

    private Map<String,String> headers = new HashMap<>();

    public HttpServletRequest(Socket socket) throws IOException, EmptyRequestException {
        this.socket = socket;
        //解析请求行
        parseRequestLine();
        //解析消息头
        parseHeaders();
        //解析正文
        parseContent();
    }

    private void parseRequestLine() throws IOException, EmptyRequestException {
        String line = readLine();
        if (line.isEmpty()){
            throw new EmptyRequestException();
        }
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        parseURI();
    }

    private void parseURI() {
        String[] data = uri.split("\\?");
        requestURI = data[0];
        if (data.length > 1){
            queryString = data[1];
            parseParameters(queryString);
        }
    }

    private void parseHeaders() throws IOException {
        while (true){
            String line = readLine();
            if (line.isEmpty()){
                break;
            }
            String[] data = line.split(":\\s");
            headers.put(data[0],data[1]);
        }
        headers.forEach((k,v) -> System.out.println("消息头:"+k+":"+v));
    }

    private void parseContent() throws IOException {
        if (headers.containsKey("Content-Length")){
            int contentLength = Integer.parseInt(headers.get("Content-Length"));
            System.out.println("正文长度:"+ contentLength);
            String contentType = headers.get("Content-Type");
            if ("application/x-www-form-urlencoded".equals(contentType)) {
                byte[] data = new byte[contentLength];
                InputStream in = socket.getInputStream();
                in.read(data);
                String line = new String(data, StandardCharsets.ISO_8859_1);
                System.out.println("正文内容:"+ line);
                parseParameters(line);
            }
        }
    }

    private void parseParameters(String line){
        try {
            line = URLDecoder.decode(line,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        for (String para : line.split("&")) {
            String[] paraArr = para.split("=", 2);
            parameters.put(paraArr[0],paraArr[1]);
        }
    }

    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char cur , pre = 'a';
        while ((d = in.read()) != -1){
            cur = (char) d;
            if (pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }


    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public String getQueryString() {
        return queryString;
    }

    public String getParameter(String name) {
        return parameters.get(name);
    }

    public Map<String, String> getHeaders() {
        return headers;
    }
}
